import 'package:flutter/material.dart';
import 'package:flutter_axrjc/datasource/network/bean/ArticleBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/HelpCenterBean.dart';
import 'package:flutter_axrjc/datasource/network/request/exp.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../datasource/network/api/KnowledgeApi.dart';
import 'state.dart';

class MyPostLogic extends GetxController with GetTickerProviderStateMixin {
  final MyPostState state = MyPostState();
  late TabController tabArticle;

  var refreshController = RefreshController(initialRefresh: true);

  var page = 1;

  @override
  void onInit() {
    super.onInit();
    tabArticle = TabController(length: 2, vsync: this);
  }

  Future<void> getPage({required bool isRefresh}) async {
    print("当前tab：${state.currentType.value}");
    if (isRefresh) {
      page = 1;
      if (state.currentType.value == 0) {
        state.helpList.clear();
      } else {
        state.knowledgeList.clear();
      }
    } else {
      page++;
    }
    try {
      if (state.currentType.value == 0) {
        //帮助
        state.helpList
            .addAll(await KnowledgeApi.getMyListHelpList(page: "$page"));
      } else {
        // 护眼知识
        state.knowledgeList
            .addAll(await KnowledgeApi.getKnowledgeList(page: "$page"));
      }
    } on ApiException catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast("$e");
    }
    if (isRefresh) {
      refreshController.refreshCompleted();
    } else {
      refreshController.loadComplete();
    }
  }

  Future<void> deleteHelp(HelpCenterBean bean) async {
    try {
      await KnowledgeApi.deletiSingleHelp("${bean.contentId}");
    } on ApiException catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast("$e");
    }
    state.helpList.remove(bean);
  }

  Future<void> deleteKnowledge(ArticleBean bean) async {
    try {
      await KnowledgeApi.deleteKnowledge("${bean.articleId}");
    } on ApiException catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast("$e");
    }
    state.knowledgeList.remove(bean);
  }
}
